package org.reborn.utils

import scala.math

object ArrayUtil {

  def resizeArray[T: Manifest](array:Array[T],arrayLength:Int,additionalSize:Int):Array[T] = {
    val remainingAmount = array.length - (additionalSize + arrayLength)
    if(remainingAmount >= 0)
      return array
    
    val extendAmount = math.max(-remainingAmount,additionalSize + remainingAmount)
    
    val newArray:Array[T] = new Array(array.length + extendAmount)
    Array.copy(array,0,newArray,0,array.length)
    newArray
  }
}

class ResizeableArray[T: Manifest](initialCapacity:Int,resizeAmount:Int){
  private var array:Array[T] = new Array(initialCapacity)
  private var arrayLength:Int = 0 
  
  def getArray = array
  def getLength = arrayLength
  
  def appendValue(value:T) = {
    resizeArray(1)
    array(arrayLength) = value
    arrayLength += 1
  }
  def appendArray(data:Array[T]) = {
    val startPos = arrayLength
    resizeArray(data.length)
    Array.copy(data,0,array,startPos,data.length)
    arrayLength += data.length
  }
  
  def replace(data:Array[T]) = {
    array = new Array(array.length + resizeAmount)
    Array.copy(data,0,data,0,data.length)
   
    arrayLength = data.length
  }
  
  private def resizeArray(additionalSize:Int){
    array = ArrayUtil.resizeArray(array,arrayLength,additionalSize)
  }
}